package com.dhms.vostok1.repository

import com.dhms.vostok1.data.spot_patrol.CheckInstrumentSpeedData
import com.dhms.vostok1.database.check_instrument.CheckInstrumentDao
import com.dhms.vostok1.service.net.NetworkApi
import kotlinx.coroutines.flow.Flow

class CheckInstrumentRepository(
    private val checkInstrumentDao: CheckInstrumentDao
) {
    val checkInstrumentSpeedData: (model: String, rpm: Long) -> Flow<List<CheckInstrumentSpeedData>> =
        { model, rpm ->
            checkInstrumentDao.getCheckInstrumentSpeedSheet(model, rpm)
        }

    suspend fun updateCheckInstrumentSpeedSheet(): List<CheckInstrumentSpeedData> {
        val res = NetworkApi.getCheckInstrumentSpeedSheetData()
        val resData = res.getOrNull()?.body()?.data
        val speedSheetData = resData?.map {
            val speedRPMIntervalInfo = it.speedRPMInterval.split("_")
            CheckInstrumentSpeedData(
                it.speedRPMInterval,
                speedRPMIntervalInfo[0],
                speedRPMIntervalInfo[1].toLong(),
                it.sampleRate,
                it.samples
            )
        } ?: DEFAULT_SPEED_SHEET
        checkInstrumentDao.insertCheckInstrumentSpeedSheet(speedSheetData)

        return speedSheetData
    }

    companion object {

        @Volatile
        private var instance: CheckInstrumentRepository? = null

        fun getInstance(checkInstrumentDao: CheckInstrumentDao) =
            instance ?: synchronized(this) {
                instance ?: CheckInstrumentRepository(checkInstrumentDao).also { instance = it }
            }

        val DEFAULT_SPEED_SHEET = listOf(
            CheckInstrumentSpeedData("GD3_0_300", "GD3", 0, 1028, 8192),
            CheckInstrumentSpeedData("GD3_300_1000", "GD3", 300, 5120, 16384),
            CheckInstrumentSpeedData("GD3_1000", "GD3", 1000, 12800, 16384),
            CheckInstrumentSpeedData("DMS1100I_0_1000", "DMS1100I", 0, 8000, 16384),
            CheckInstrumentSpeedData("DMS1100I_1000", "DMS1100I", 1000, 16000, 16384),
        )
    }
}